<template>
  <div class="Server">
    <el-row>
      <!-- 头部2，创建按钮 及搜索框 -->
      <el-col :span="24">
        <el-card class="Server-head-card" shadow="never" :body-style="{padding:'10px'}">
          <!-- float属性，会将多个同级标签放在同一行 -->
          <div style="float: left;margin-right:10px;">
            <el-button  size="small" type="primary" icon="Edit"  @click="create_projects()">创建项目</el-button>
          </div>
          <div>
            <el-input class="Server-head-search" size="small" clearable placeholder="请输入" v-model='searchValue'></el-input>
            <el-button size="small" type="primary" plain icon="Edit" @click="GetListApps()">搜索</el-button>
          </div>
        </el-card>
      </el-col>
      <el-col :span="24">
        <div>
          <el-card class="Server-body-card" shadow="never" :body-style="{padding:'5px'}">
            <el-table
                style="width:100%;font-size:12px;margin-bottom:10px;"
                :data="GetListApps_data"
                v-loading="appLoading">
              <el-table-column width="20"></el-table-column>

              <el-table-column align=left label="项目列表">
                <template v-slot="scope">
                  <div>{{ scope.row.regionaname }}</div>
                </template>
              </el-table-column>

              <el-table-column align=left label="项目环境">
                <template v-slot="scope">
                  <div>{{ scope.row.selectedEnv }}</div>
                </template>
              </el-table-column>

              <el-table-column align="left" label="镜像区域">
                <template v-slot="scope">
                  <div>{{ scope.row.imagesregion }}</div>
                </template>
              </el-table-column>

              <el-table-column align="left" label="应用数量">
                <template v-slot="scope">
                  <div>{{ scope.row.AppItems.length }}</div>
                </template>
              </el-table-column>


<!--              <el-table-column align=left label="项目列表">-->
<!--                <template v-slot="scope">-->
<!--                  <div v-for="(item, index) in scope.row.AppItems" :key="item.id">-->
<!--                    {{ item.name }} - Version: {{ item.selectedVersion }}-->
<!--                  </div>-->
<!--                </template>-->
<!--              </el-table-column>-->


              <el-table-column align=center label="操作" min-width="150">
                <template v-slot="scope">
                  <el-button size="small" style="border-radius:5px;" icon="Edit" type="primary" plain @click="Run_Apps(scope.row)" >执行</el-button>
                  <el-button size="small" style="border-radius:5px;" icon="Edit" type="primary" plain @click="Copy_pip(scope)">复制</el-button>
                  <el-button size="small" style="border-radius:5px;" icon="Edit" type="primary" plain @click="Update_pip(scope,updataserverFunc)">修改</el-button>
                  <el-button size="small" style="border-radius:5px;" icon="Edit" type="danger"  plain @click="Delete_pip(scope.row )">删除</el-button>
                </template>
              </el-table-column>

            </el-table>
            <el-pagination
                class="Server-body-pagination"
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="pagesizeList"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :prev-click="getServers"
                :total="ServerTotal">
            </el-pagination>
          </el-card>
        </div>
      </el-col>
    </el-row>


    <!-- 创建 -->

    <el-dialog
        v-model="createserverDrawer"
        width="1200"
        :before-close="handleClose"
        title="创建项目部署"
    >

      <template #default>

        <el-form-item label="项目名称">
          <el-input v-model="this.create_app.regionaname" placeholder="请输入名称" style="width: 200px;" />
        </el-form-item>

        <el-form-item label="镜像区域">
          <el-select v-model="imagesregion" placeholder="请选择你的区域">
            <el-option
                v-for="(item, index) in regions"
                :key="index"
                :label="item"
                :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item class="deploy-create-form" label="部署环境" prop="installenv">
          <el-select v-model="selectedEnv" filterable placeholder="请选择环境">
            <el-option
                v-for="env in envs"
                :key="env"
                :label="env"
                :value="env">
            </el-option>
          </el-select>
        </el-form-item>


        <el-select v-model="input_APP" multiple placeholder="Select Names" style="width: 300px;">
          <el-option
              v-for="item in formattedOptions"
              :key="item.name"
              :label="item.name"
              :value="formatValue(item)">
          </el-option>
        </el-select>


        <el-button size="small" type="primary" icon="Edit" @click="inputApps(input_APP)">导入指定应用</el-button>



        <el-button size="small" type="primary" icon="Edit" @click="importApps">导入所有应用</el-button>


        <el-card class="App_name-body-card" shadow="never" :body-style="{padding:'5px'}">
          <el-table
              style="width:100%;font-size:12px;margin-bottom:10px;"
              :data="AddAppList"
              v-loading="appLoading">
            <el-table-column width="20"></el-table-column>

            <el-table-column align="left" label="应用列表">
              <template v-slot="scope">
                <p :class="'appname-body'" >{{ scope.row.name }}</p>
              </template>
            </el-table-column>

            <el-table-column align="center" label="版本" min-width="100">
              <template v-slot="scope">
                <el-select v-model="scope.row.selectedVersion" placeholder="请选择版本">
                  <el-option
                      v-for="(tag, index) in scope.row.tags"
                      :key="index"
                      :label="tag"
                      :value="tag">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>


            <el-table-column align=center label="操作" min-width="120">
              <template v-slot="scope">
                <el-button size="small" icon="Edit" type="danger" plain @click="handleConfirm(scope, '删除')">删除</el-button>
              </template>
            </el-table-column>

          </el-table>
          <el-pagination
              class="Servergroup-body-pagination"
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="pagesizeList"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :prev-click="getServergroups"
              :total="ServergroupTotal">
          </el-pagination>
        </el-card>
      </template>



      <template #footer>
        <el-button @click="createserverDrawer=false">取消</el-button>
        <el-button type="primary" @click="CreateApps()">立即创建</el-button>
      </template>

    </el-dialog>

<!--    </el-drawer>-->
<!--     修改 -->
  </div>

</template>

<script>
import common from "../../common/Config";
import httpClient from '@/request';


export default {
  data() {
    return {
      regionaname:"ysl",
      regions: "",
      imagesregion: "", // To store the selected option
      AddAppList:[],

      input_APP: "", // 用于存储用户选择的值
      loading: false, // 用于控制加载状态
      options: [],
      appointapps: [],

      GetListApps_data:"",

      envs: ['DEV', 'SIT', 'UAT', 'PREPROD'],
      selectedEnv:"",


      //创建项目列表
      create_app :{
        geturl: common.getlistapps,
        createurl: common.cicd_projects,
        regionaname:"",
        imagesregion:"",
        selectedEnv:"",
        AddAppList:[],
      },

      //运行项目列表
      run_apps :{
        runapprul: common.runapps,
        regionaname:"",
        imagesregion:"",
        selectedEnv:"",
        AddAppList:[],
      },

      delete_pips :{
        delete_pips_url: common.delete_pips,
        regionaname:"",
        imagesregion:"",
        selectedEnv:"",
        AddAppList:[],
      },



      harbor :{
        Harbor_projects_url: common.harbor_projects,
        Harbor_prepositories_url: common.harbor_prepositories,
        Harbor_images_list_url: common.harbor_images_list,
        data:{
          projectname:"",
          imagesname:"",
        }
      },


      //编辑器配置
      currentRow: '',
      sshDialogVisible: false,
      createserverDrawer: false,
      middnamespaceValue: '',
      appnamespaceValue: '',
      namespaceListUrl: common.k8sNamespaceList,

      createserverData: {},

      cmOptions: common.cmOptions,
      contentYaml: '',
      //分页
      currentPage: 1,
      pagesize: 10,
      pagesizeList: [10, 20, 30],
      searchValue: '',
      appLoading: false,
      authentication:'',

      dynamicValidateForm: {
        domains: [
          {
            key: 1,
            value: '',
          },
        ],
        email: '',
      },
    }
  },



//镜像列表数据格式输出模版
  computed: {
    formattedOptions() {
      return this.options.map(item => {
        let tags = Array.isArray(item.tags) ? item.tags : item.tags.split(', ');
        return {
          name: item.name,
          tags: tags.map(tag => tag.trim())
        };
      });
    }
  },



  methods: {
    //镜像列表数据输出
    formatValue(item) {
      return JSON.stringify({ name: item.name, tags: item.tags });
    },

    inputApps(selectedTags) {
      const parsedSelectedTags = selectedTags.map(tagStr => JSON.parse(tagStr));
      this.AddAppList = parsedSelectedTags;
    },

    importApps() {
      this.AddAppList = [...this.options]; // Assuming input_APP is an array of objects similar to AddAppList items
      //this.AddAppList = this.options.map(option => option.name); // 使用map函数遍历options数组
      console.log(this.AddAppList)
    },

    handleConfirm(scope, action) {
      console.log(scope.row)
      if (action === '删除') {
        const index = this.AddAppList.findIndex(app => app.name === scope.row.name);
        if (index !== -1) {
          this.AddAppList.splice(index, 1); // Delete the found application
        }
      }
    },

    CreateApps() {
    //过滤去掉多余tags列表字段
    const modifiedAppList = this.AddAppList.map(app => {
      const { tags, ...rest } = app;
      return rest;
    });


    this.create_app.imagesregion = this.imagesregion
    this.create_app.AddAppList = modifiedAppList

    this.create_app.selectedEnv = this.selectedEnv
    console.log('Regions Name:', this.create_app);

      httpClient.post(this.create_app.createurl, this.create_app)
          .then(res => {
            this.$message.success({
              message: res.msg
            })
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
          .finally(() => {
            //this.getServergroups()
            this.GetListApps()
            this.createserverDrawer = false
          })
    },

    GetListApps() {
      httpClient.get(this.create_app.geturl)
          .then(res => {
            this.GetListApps_data = res.data
            console.log(this.GetListApps_data)
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },



    Run_Apps(row) {
      this.run_apps.AddAppList = row.AppItems
      httpClient.post(this.run_apps.runapprul, this.run_apps)
          .then(res => {
            this.$message.success({
              message: res.msg
            })
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
          .finally(() => {
            this.GetListApps()
          })
    },


    Delete_pip(row) {
      this.delete_pips.regionaname = row.regionaname
      console.log(row);
      console.log(this.delete_pips);

      httpClient.post(this.delete_pips.delete_pips_url, this.delete_pips)
          .then(res => {
            this.$message.success({
              message: res.msg
            })
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
          .finally(() => {
            this.GetListApps()
          })
    },



    UpdateApps() {
      //过滤去掉多余tags列表字段
      const modifiedAppList = this.AddAppList.map(app => {
        const { tags, ...rest } = app;
        return rest;
      });

      this.create_app.imagesregion = this.imagesregion
      this.create_app.AddAppList = modifiedAppList
      console.log('Regions Name:', this.create_app);

      httpClient.post(this.create_app.createurl, this.create_app)
          .then(res => {
            this.$message.success({
              message: res.msg
            })
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
          .finally(() => {
            //this.getServergroups()
            this.GetListApps()
            this.createserverDrawer = false
          })
    },


    resetForm() {
      this.$refs.formRef.resetFields();
    },


    //读取Harbor列表
    create_projects() {
      this.harbor_projects()
      this.createserverDrawer = true
    },


    harbor_projects() {
      httpClient.get(this.harbor.Harbor_projects_url)
          .then(res => {
            this.regions = res.data
            console.log(this.regions)
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },

    harbor_prepositories(imagesregion) {
      this.harbor.data.projectname = imagesregion
      httpClient.get(this.harbor.Harbor_prepositories_url,{params: this.harbor.data})
          .then(res => {
            this.options = res.data
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },

    // harbor_images_list() {
    //   httpClient.get(this.harbor.Harbor_images_list_url,{params: this.harbor.data})
    //       .then(res => {
    //         this.ServergroupList = res.data
    //       })
    //       .catch(res => {
    //         this.$message.error({
    //           message: res.msg
    //         })
    //       })
    // },


    //创建
    createserverpipFunc() {
      const uniqueMiddndata =  this.middndata.filter((obj, index) => {
        return index ===  this.middndata.findIndex(o => obj.name === o.name && obj.ClusterDns === o.ClusterDns);
      });

      console.log(uniqueMiddndata);
      //console.log(this.appsdata)

      this.middndata.splice(0);
      this.activeStep = 1
      this.createserverDrawer = false
      this.createhostpipDrawer = false


    },

    //分页属性
    handleSizeChange(size) {
      this.pagesize = size;
      this.getNamespaces()
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.getNamespaces()
    },
    //选择判断
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(() => {
            done();
          })
          .catch(() => {});
    },

    // handleConfirm(obj, operateName, fn) {
    //   this.confirmContent = '确认继续 ' + operateName + ' 操作吗？'
    //   this.$confirm(this.confirmContent,'提示',{
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //   })
    //       .then(() => {
    //         fn(obj)
    //       })
    //       .catch(() => {
    //         this.$message.info({
    //           message: '已取消操作'
    //         })
    //       })
    // },
  },
  //注册子组件
  // components: {
  //   MiddlewareItem,
  //   Appservers
  // },

  //监听如果集群发生改变则刷新命名空间数据列表
  watch: {
    imagesregion(newVal, oldVal) {
      this.harbor_prepositories(newVal);
    }
  },

  mounted() {
    this.GetListApps()
  }
}
</script>


<style scoped>

.appname-body {
  margin: 0px;
  color: #4795EE;
}




.Server-head-card,.Server-body-card {
  border-radius: 10px;
  margin-bottom: 20px;
}
.Server-head-search {
  width:160px;
  margin-right:10px;
}

</style>